
// 插件的ID和密钥
const pluginId = "z62hjkrw";
const pluginSecret = "dwmtK9a9X5ysI3WZgv3vb7Hm52YNm249";

// 获取用户信息
export async function getUserInfo(){
    // 本地开发临时方案
    // return {
    //     "avatar": "https://res.u-tools.cn/assets/avatars/lpW3lcjLQXVxuXya.png",
    //     "member": 0,
    //     "nickname": "大話家",
    //     "open_id": "46bdde6b0a337e78c7868bf310159a82",
    //     "timestamp": 1682761294
    // };
    let resToken = await utools.fetchUserServerTemporaryToken();
    
    let params = {
        plugin_id: pluginId,
        access_token: resToken.token,
        timestamp: Math.floor(Date.now() / 1000)
    };
    let sign = await getServerSign(params, pluginSecret);
    params.sign = sign;
    
    return new Promise((resolve, reject) => {
        uni.request({
          url: 'https://open.u-tools.cn/baseinfo',
          method: 'GET',
          header: {
            'Accept': 'application/json'
          },
          data: params,
          success: function (res) {
            resolve(res.data.resource);
          },
          fail: function (err) {
            reject(err);
          }
        })
    });
}

// 获取uTools服务器验证的签名。具体参考官方文档1.3节 https://u.tools/docs/developer/server-api.html
export function getServerSign(params, secret) {
    let encodedParams = encodeParams(params);
    return hmacSha256(encodedParams, secret);
}

// 请求参数排序并编码
export function encodeParams(params) {
    let sortedParams = {};
    Object.keys(params).sort().forEach(key => {
        sortedParams[key] = params[key]
    })

    let parts = [];
    Object.keys(sortedParams).forEach(key => {
        let value = sortedParams[key]
        if (value !== null && value !== undefined) {
            parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
        }
    })
    return parts.join('&');
}

// hmacSha256加密
export function hmacSha256(data, key) {
    let encoder = new TextEncoder();
    let secretKey = crypto.subtle.importKey(
        'raw',
        encoder.encode(key), // 注意此处为二进制数据格式
        { name: 'HMAC', hash: { name: 'SHA-256' } }, // 指定算法
        true,
        ['sign', 'verify']
    );

    return secretKey.then(key => {
        return crypto.subtle.sign(
            { name: 'HMAC' }, 
            key, 
            encoder.encode(data)
        );
    }).then(signature => {
        return Array.from(new Uint8Array(signature))
            .map(b => b.toString(16).padStart(2, '0')).join('');
    });
}